// 用户数据模型
module.exports = class User extends require("./model") {
  /**
   * 登陆
   * @param {string} username 登陆账号
   * @param {string} password  登陆密码
   */
  static login(username, password) {
    return new Promise((resolve, reject) => {
      let sql =
        "SELECT id,username,realname FROM `users` WHERE username = ? AND PASSWORD = ?";
      this.query(sql, [username, password])
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  /**
   * 获取用户列表
   */
  static UserList() {
    return new Promise((resolve, reject) => {
      let sql = "SELECT id,username,realname FROM `users`";
      this.query(sql)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  /**
   * 删除用户
   * @param {integer} id 用户id
   */
  static delUser(id) {
    return new Promise((resolve, reject) => {
      let sql = "DELETE FROM users WHERE id = ?";
      this.query(sql, id)
        .then((res) => {
          resolve(res.affectedRows);
        })
        .catch((err) => {
          console.log(`删除用户失败：${err.message}`);
          reject(err);
        });
    });
  }
  /**
   *
   * @param {Object} userList 用户对象
   */
  static userAdd(userList) {
    return new Promise((resolve, reject) => {
      let sql = "INSERT INTO users SET ?";
      this.query(sql, userList)
        .then((res) => {
          resolve(res.affectedRows);
        })
        .catch((err) => {
          console.log(`添加用户失败：${err.message}`);
          reject(err);
        });
    });
  }
  // 编辑用户
  static editUser(user) {
    return new Promise((resolve, reject) => {
      let { username, realname, id, password } = user;
      password = parseInt(password);
      let sql = "UPDATE users SET username = ?,realname = ?";
      sql += password ? ',`password`='+password : "";
      sql += " WHERE id = ?";
      this.query(sql, [username, realname, id])
        .then((res) => {
          resolve(res.affectedRows);
        })
        .catch((err) => {
          console.log(`编辑文章失败：${err.message}`);
          reject(err);
        });
    });
  }
};
